"""
---------------------------------------------------------------------
- File: service.py
- Date: 2025/9/26
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description:
---------------------------------------------------------------------
"""

from typing import List

# model
from app.models.system_manage.menu import Menu

# pydantic
from .schemas import MenuTree, MenuIn

# utils
from app.curd.orm_crud import OrmCRUD


class MenuService:

    @staticmethod
    async def add_menu(menu_data: MenuIn) -> Menu:
        menu = await OrmCRUD(Menu).create(**menu_data.model_dump())
        return menu

    @staticmethod
    async def delete_menu(menu_id: int) -> None:
        result = await OrmCRUD(Menu).delete(menu_id)
        return result

    @staticmethod
    async def update_menu(menu_id: int, menu_in: MenuIn) -> Menu | None:
        menu = await OrmCRUD(Menu).get(menu_id)
        if menu is None:
            return None
        await OrmCRUD(Menu).update(menu_in.model_dump(), menu_id)
        # 重新查询更新后的菜单信息
        new_menu = await OrmCRUD(Menu).get(menu_id)
        if new_menu is None:
            return None
        return new_menu

    @staticmethod
    async def get_menu_tree() -> List[MenuTree]:
        all_menus = await Menu.all().order_by("order")

        menu_dict = {}
        for menu in all_menus:
            menu_data = MenuTree.model_validate(menu)
            menu_dict[menu.id] = menu_data
            menu_dict[menu.id].children = []  # 确保children是空列表
        tree = []
        for menu in all_menus:
            menu_node = menu_dict[menu.id]
            if menu.parent_id == 0:
                tree.append(menu_node)
            else:
                parent = menu_dict.get(menu.parent_id)
                if parent:
                    parent.children.append(menu_node)

        return tree
